﻿using System;
using TNet;
using UnityEngine;

[RequireComponent(typeof(TNManager))]
public class TNAutoJoin : MonoBehaviour
{
    public bool allowUDP = true;
    public int channelID = 1;
    public bool connectOnStart = true;
    public string disconnectLevel;
    public string failureFunctionName;
    public string firstLevel = "Example 1";
    public static TNAutoJoin instance;
    public string serverAddress = "127.0.0.1";
    public int serverPort = 0x1407;
    public string successFunctionName;

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
    }

    public void Connect()
    {
        Screen.sleepTimeout = -1;
        TNManager.Connect(this.serverAddress, this.serverPort);
    }

    private void OnNetworkConnect(bool result, string message)
    {
        if (result)
        {
            if (this.allowUDP)
            {
                TNManager.StartUDP(UnityEngine.Random.Range(0x2710, 0xc350));
            }
            TNManager.JoinChannel(this.channelID, this.firstLevel);
        }
        else if (!string.IsNullOrEmpty(this.failureFunctionName))
        {
            object[] parameters = new object[] { message };
            UnityTools.Broadcast(this.failureFunctionName, parameters);
        }
        else
        {
            Debug.LogError(message);
        }
    }

    private void OnNetworkDisconnect()
    {
        if (!string.IsNullOrEmpty(this.disconnectLevel) && (Application.loadedLevelName != this.disconnectLevel))
        {
            Application.LoadLevel(this.disconnectLevel);
        }
    }

    private void OnNetworkJoinChannel(bool result, string message)
    {
        if (result)
        {
            if (!string.IsNullOrEmpty(this.successFunctionName))
            {
                UnityTools.Broadcast(this.successFunctionName, new object[0]);
            }
        }
        else
        {
            if (!string.IsNullOrEmpty(this.failureFunctionName))
            {
                object[] parameters = new object[] { message };
                UnityTools.Broadcast(this.failureFunctionName, parameters);
            }
            else
            {
                Debug.LogError(message);
            }
            TNManager.Disconnect();
        }
    }

    private void Start()
    {
        if (this.connectOnStart)
        {
            this.Connect();
        }
    }
}

